package leader

import (
	"gitverse.ru/synapse/kubelatte/pkg/grpc"
	"gitverse.ru/synapse/kubelatte/pkg/operator/controllers"
	initManager "gitverse.ru/synapse/kubelatte/pkg/operator/controllers/manager"
	"net/http"
	"testing"
)

var syncController *grpc.SyncController

func Test_readyz(t *testing.T) {
	defer func() {
		syncController = nil
	}()

	t.Run("nil syncController", func(t *testing.T) {
		syncController = nil
		err := readyz(nil)
		if err == nil {
			t.Fatal("Err expected to be not nil")
		}
	})

	t.Run("zero last time", func(t *testing.T) {
		syncController = &grpc.SyncController{LastTime: 0}
		err := readyz(nil)
		if err == nil {
			t.Fatal("Err expected to be not nil")
		}
	})

	t.Run("not nil syncController and not allowed", func(t *testing.T) {
		syncController = &grpc.SyncController{LastTime: 5}
		initManager.PermissionsSet = false
		err := readyz(&http.Request{})
		if err == nil {
			t.Fatal("Expected error")
		}
	})
	t.Run("not nil syncController and allowed", func(t *testing.T) {
		syncController = &grpc.SyncController{LastTime: 40}
		initManager.PermissionsSet = true
		err := readyz(&http.Request{})
		if err != nil {
			t.Fatal("Err expected to be nil")
		}
	})
}

func Test_healthz(t *testing.T) {
	var wantErr bool
	initMgr = initManager.GetInitManager()
	controllers.KbltMutator = "false"

	t.Run("No_resources_in_cluster", func(t *testing.T) {
		wantErr = false

		if err := healthz(nil); (err != nil) != wantErr {
			t.Errorf("healthz() error = %v, wantErr %v", err, wantErr)
		}
	})

	t.Run("Each_controller_is_not_initialized", func(t *testing.T) {
		wantErr = false

		if err := healthz(nil); (err != nil) != wantErr {
			t.Errorf("healthz() error = %v, wantErr %v", err, wantErr)
		}
	})

	t.Run("Each_controller_is_not_started", func(t *testing.T) {
		wantErr = true
		controllers.KbltMutator = "true"
		defer func() { controllers.KbltMutator = "false" }()

		triggerR = &controllers.TriggerReconciler{}
		templateR = &controllers.TemplateReconciler{}
		scopeR = &controllers.ScopeReconciler{}
		if err := healthz(nil); (err != nil) != wantErr {
			t.Errorf("healthz() error = %v, wantErr %v", err, wantErr)
		}
	})
}
